package com.springbatch.springbatch;

import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.JobRegistry;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ImportResource;

import java.time.LocalDate;
import java.util.*;

import static java.lang.String.format;

@SpringBootApplication
@ImportResource(locations = {"classpath:jobs/Job*.xml", "classpath:spring-batch.xml"} )
public class SpringbatchApplication {


    public static void main(String[] args) {
        String jobName = "A13111001";
        if(args.length>0 && StringUtils.isEmpty(args[0]))
            jobName= args[0];

        try {
            ConfigurableApplicationContext context = SpringApplication.run(SpringbatchApplication.class, args);
            JobRegistry jobRegistry = context.getBean(JobRegistry.class);
            Job job1 = jobRegistry.getJob("A13111001");

            JobLauncher jobLauncher = context.getBean(JobLauncher.class);
            JobExecution jobExecution = jobLauncher.run(job1, new JobParameters());

            if (!jobExecution.getExitStatus().equals(ExitStatus.COMPLETED)) {
                throw new RuntimeException(format("  Job execution failed." ));
            }
        } catch (Exception e) {
            throw new RuntimeException(format("  Job execution failed." ));
        }

    }

//    public static JobParameters getUniqueJobParameters() {
//        Map<String, JobParameter> parameters = new HashMap<>();
//        parameters.put("random", new JobParameter((long) (Math.random() * 100000)));
//        parameters.put("datetime", new JobParameter((String) ( LocalDate.now().toString())));
//        return new JobParameters(parameters);
//    }
}
